<template>
  <!-- 评论输入表单 -->
  <div class="form">
    <h3>
      发表评论和建议
      <el-button v-show="this.realParentCommentId !== -1" class="m-small" size="mini" type="primary"
                 @click="toSendParentId()">取消回复
      </el-button>
    </h3>
    <el-form ref="formRef" :model="commentForm" :rules="rules" size="small">
      <el-form-item prop="content">
      <el-input v-model="commentForm.content" :class="'textarea'" :rows="5" :validate-event="false" maxlength="50"
                placeholder="评论千万条，友善第一条" show-word-limit type="textarea"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="6">
        <el-form-item prop="rate" style="margin-left: 50px">
          <el-rate v-model="value" :colors="colors"  ref="rate"></el-rate>
        </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="nickname">
<!--            <el-popover ref="nicknamePopover" content="输入QQ号将自动拉取昵称和头像" placement="bottom" trigger="focus"></el-popover>-->
            <el-input v-model="commentForm.nickname" v-popover:nicknamePopover :validate-event="false" placeholder="QQ或昵称（必填）"
                      @blur="onInputBlur" ref="qq">
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :offset="1" :span="5">
          <el-form-item>
            <!-- 接口节流  -->
            <el-button size="medium" type="primary"   @mouseenter.native="beforePost" @click="postForm">发表评论</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>


  </div>
</template>

<script>

import {mapState} from "vuex";

export default {
  name: "CommentForm",
  props: {
    realParentCommentId: {
      type: Number,
      default: '-1'
    },
    realParentCommentNickname: {
      type: String,
      default: ""
    }

  },
  computed:{
    ...mapState(['userInfo','token']),
  },
  data() {
    return {
      commentForm: {
        content: "",
        nickname: "游客",
        rate: "",
        avatar: "",
        parentCommentId: this.realParentCommentId,
        isAdminComment: -1,
        qq: "",
        parentCommentNickname: this.realParentCommentNickname
      },
      rules: {
        nickname: [
          {required: true, message: '请输入qq',trigger: 'blur'},
          {max: 15, message: '昵称不可多于15个字符', trigger: 'blur'}
        ],
        rate: [
          {required: true, message: '请进行评分',trigger: 'blur'},
        ],
        content: [
          {required: true, message: '请进行评论',trigger: 'blur'},
        ]
      },
      value:null,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900']

    }
  },
  methods: {
    //设计哈希函数
    //1>将字符串转成比较大的数字：hashCode
    //2>将大的数字hashCode压缩到数组范围
    hashFunc(str, size) {
      //1.定义hashCode变量
      var hashCode = 0
      //2.霍纳算法，来计算 hashCode的值
      for (var i = 0; i < str.length; i++) {
        hashCode = 37 * hashCode + str.charCodeAt(i) //获取编码
      }
      //3.取余状态
      var index = hashCode % size + 1
      return index
    },
    //取消回复 向父组件传值 并设置评论父id
    toSendParentId() {
      this.$emit('parentEvent', '取消回复了')
      //console.log("取消")
      this.commentForm.parentCommentId = -1
    },
    //失去焦点 自动获取qq昵称和头像 或者非qq设置随机头像
    onInputBlur() {
      //判断是否是qq号码
      // const _this = this
      // var qq = this.commentForm.nickname
      // if (!isNaN(Number(qq)) && qq.length > 4 && qq.length < 12) {
      //   console.log(_this.commentForm.avatar)
      //   this.$axios.get('https://api.usuuu.com/qq/' + qq).then(res => {
      //     if (res.data) {
      //       _this.commentForm.nickname = res.data.data.name
      //       _this.commentForm.avatar = res.data.data.avatar
      //       _this.commentForm.qq = res.data.data.qq
      //     }
      //   })
      // }

    },
    //提交之前检查头像地址是否为空
    beforePost() {
      const _this = this
      if (this.commentForm.avatar == "") {
        this.onInputBlur()
      }
      this.commentForm.rate=_this.value
    },

    //提交评论
    postForm() {
      //console.log(JSON.stringify(this.commentForm))
      //表单校验
      const _this = this
      this.onInputBlur()
      if(_this.commentForm.avatar===""||_this.commentForm.avatar===null ){
        _this.commentForm.avatar="https://q1.qlogo.cn/g?b=qq&nk=1604675063&s=100";
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // console.log(JSON.stringify(this.commentForm))
          //判断是否为管理员(博主)
          if (this.commentForm.isAdminComment === 1) {
            this.commentForm.avatar = "http://localhost:8181/profile/avatar/2022/02/23/d2cd51ae-e259-4077-8e18-a5381d2da591.jpeg"
          }
          const _this = this
          this.$axios.post(this.$base_url+'comment/add', this.commentForm).then(res => {
            //console.log(res)
            if (res.data.code === 200) {
              this.$message({
                message: res.data.data,
                type: 'success'
              });
              location.reload()
            } else {
              this.$message.error(res.data.msg);
            }
          })
          // //alert('submit!');
          // //成功后清空表单
          // this.$refs.formRef.resetFields();
          // this.commentForm.content = ""
          // this.commentForm.qq = ""
          // this.commentForm.avatar = ""
        } else {
          this.$message.error("请输入正确的评论");
          return false;
        }
      });
    }
  },
  watch: {
    //监控props 但是好像没用额， 因为为在父类中没改动
    realParentCommentId: function (newVal) {
      this.commentForm.parentCommentId = newVal
      // console.log(JSON.stringify(this.commentForm))
    }
  },
  created() {
    if (this.$store.getters.getUser && this.token!=="") {
      if(this.$store.getters.getUser.role==="role_root") {
        this.commentForm.isAdminComment = 1;
      }
      if (this.$store.getters.getUser!==""&&this.$store.getters.getUser!==null){
        this.commentForm.nickname=this.$store.getters.getUser.username
        this.commentForm.avatar='http://localhost:8181'+this.$store.getters.getUser.avatar
      }
    }
  },
}
</script>

<style scoped>
.form h3 {
  margin: 5px;
  font-weight: 500 !important;
}
.form .m-small {
  margin-left: 5px;
  padding: 4px 5px;
}
.el-form .textarea {
  margin-top: 5px;
  margin-bottom: 15px;
}
.el-form textarea {
  padding: 6px 8px;
}
.el-form textarea, .el-form input {
  color: black;
}
.el-form .el-form-item__label {
  padding-right: 3px;
}
</style>